﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace HubbleTelescope.Framework
{
    /// <summary>
    /// Class enabling simple ICommand implementation, with explicit InvalidateCanExecute()
    /// 
    /// Shamelessly took and modified this class from Rob Eisenberg's blog here:
    ///     http://devlicio.us/blogs/rob_eisenberg/archive/2009/11/13/mvvm-study-part-4-naked-wpf.aspx
    /// </summary>
    public class DelegateCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        public event EventHandler CanExecuteChanged = delegate { };

        public DelegateCommand(Action execute)
            : this(execute, () => true)
        {
            _execute = execute;
        }

        public DelegateCommand(Action execute, Func<bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(object parameter)
        {
            _execute();
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute();
        }

        public void InvalidateCanExecute()
        {
            Framework.Execute.OnUIThread(() => CanExecuteChanged(this, EventArgs.Empty));
        }
    } 
}
